﻿using System;
using System.Xml.Linq;

namespace SPQueryToSql.Extensions
{
    internal static class XElementExtensions
    {
        public static string AttributeValueString(this XElement element, string attributeName, string defaultValue)
        {
            var attr = element.Attribute(attributeName);
            var res = attr != null
                     ? attr.Value
                     : defaultValue;
            return res;
        }

        public static bool AttributeValueBool(this XElement element, string attributeName, bool defaultValue)
        {
            var attr = element.Attribute(attributeName);
            var res = attr != null
                     ? attr.Value.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)
                     : defaultValue;
            return res;
        }

        public static bool? AttributeValueNullableBool(this XElement element, string attributeName)
        {
            var attr = element.Attribute(attributeName);
            var res = attr != null
                     ? attr.Value.Equals("TRUE", StringComparison.InvariantCultureIgnoreCase)
                     : (bool?) null;
            return res;
        }

        public static Guid AttributeValueGuid(this XElement element, string attributeName, Guid defaultValue)
        {
            var attr = element.Attribute(attributeName);
            var res = attr != null
                     ? new Guid(attr.Value)
                     : defaultValue;
            return res;
        }

        public static int AttributeValueInt(this XElement element, string attributeName, int defaultValue)
        {
            var attr = element.Attribute(attributeName);
            if(attr == null)return defaultValue;
            int val;
            return int.TryParse(attr.Value, out val)
                       ? val
                       : defaultValue;
        }
    }
}
